# 这是一个示例 Python 脚本。

# 按 Shift+F10 执行或将其替换为您的代码。
# 按 按两次 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。

import re
import time
import traceback

from amz_info import amz_info
from excel_util import excel_util
from util import logging

thisTime = time.strftime("%Y%m%d", time.localtime())
colos = {'yell': 'FFFF00', 'write': 'FFFFFF', 'red': 'FF0000'}


def start():
    # 初始化加拿大和美国网页的浏览器
    usChrom = amz_info()
    usChrom.amzInfo('us')
    # 修改配送地
    # usChrom.setDeliver()
    caChrom = amz_info()
    caChrom.amzInfo('ca')
    chromMap = {'us': usChrom, 'ca': caChrom}
    # chromMap = {'ca': caChrom}

    # 未找到商品信息的ASIN
    noInfoShop = []
    try:
        try:
            e = excel_util()
            maxRows, maxColumn = e.getMaxTable()
            for i in range(2, maxRows + 1):
                # 读取excel表格数据
                datas = e.getRowsDate(i)
                asin = datas[1]
                # 商品国家信息
                country = re.sub('\d', '', datas[0]).lower()
                chrom = chromMap[country]
                logging.info(f'国家:{country},亚马逊产品ASIN:{asin}')
                # 搜索商品
                if not chrom.seaAsin(asin):
                    noInfoShop.append(asin)
                    continue
                # 获取排名 --写入数据
                rans = chrom.getRanking()
                # 获取评论数
                coms = chrom.getComment()
                logging.info(f'商品{asin}排名：{rans},评论{coms}')
                # 写入排名数据
                ransLen = len(rans) if len(rans) <= 2 else 2
                for j in range(ransLen):
                    # 处理第及列数据
                    column = 9 if ransLen == 1 else 8 + j
                    logging.info(f'处理{i}行{column}列数据，新排名：{rans[j]}')
                    newRans = saveRans(datas[column-1],rans[j])
                    if newRans:
                        e.saveCellData(newRans[0],i,column,bgColor=newRans[1])
                # 写入评论数据
                e.saveCellData(coms[0], i, 11, bgColor=colos['yell'] if coms[0] != datas[10] else colos['write'])
                e.saveCellData(coms[1], i, 12, bgColor=colos['yell'] if coms[1] != datas[11] else colos['write'])
        finally:
            e.closeExcel()
            e.saveNewFile(f'../excel/AMZ账号在售情况-姚洁琪-{thisTime}.xlsx')
    except Exception as e:
        traceback.print_exc()
    # 将未找到的商品ASIN写入到本地文件
    logging.info(f'将未找到商品信息的ASIN写入文件:{noInfoShop}')
    with open('./notInfoASIN.text', 'w', encoding='utf-8') as file:
        for asin in noInfoShop:
            file.write(asin + '\n')
    logging.info(f'未找到商品信息的ASIN写入文件完成')


def saveRans(oldRans: str, newRans: str) -> (str, str):
    """
    判断当前排名升降，组装数据并返回颜色和修改后的排名
    :param oldRans: 旧排名数据
    :param newRans: 新排名数据
    :return:
    """
    # 当前唔排名，则不做操作
    if newRans == '--':
        return False
    ransText = '#'
    if oldRans == '--' or oldRans == '——' or oldRans is None or oldRans == '':
        ransText += str(newRans) + '-' + thisTime
        return ransText, colos['yell']
    ransList = oldRans.split('\n')
    oldRanLen = len(ransList)
    frontRans = re.sub('\D','',ransList[oldRanLen-1].split('-')[0])
    if frontRans == '':
        return False
    frontRans = int(frontRans)
    newRans = int(newRans)
    thisColor = colos['write']
    if frontRans > newRans:
        thisColor=colos['yell']
    elif frontRans<newRans:
        thisColor = colos['red']
    ransList.append(ransText + str(newRans) + '-' + thisTime)
    if len(ransList) > 8:
        del ransList[0]
    return '\n'.join(ransList),thisColor
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    start()

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
